const path = require('path')

const packageJson = require('./package.json')
const version = packageJson.version

const CompressionPlugin = require('compression-webpack-plugin')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const isDev = process.env.MODE === 'development'

export default {
  render: {
    resourceHints: false,
  },
  env: {
    MODE: process.env.MODE,
    NODE_ENV: process.env.MODE,
    version: version,
  },
  hooks: {
    generate: {
      page(page) {
        const cheerio = require('cheerio')
        const $ = cheerio.load(page.html, { decodeEntities: false })

        const attrs = [
          'data-n-head-ssr',
          'data-n-head',
          'data-hid',
          'data-vue-ssr-id',
          'data-server-rendered',
        ]

        attrs.forEach((value) => {
          $('*[' + value + ']').removeAttr(value)
        })

        page.html = $.html()
      },
    },
  },
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: 'Toolify - Find The Exact AI Tool For Your Needs',
    resourceHints: false,
    htmlAttrs: {
      lang: 'en',
    },
    meta: [
      { charset: 'utf-8' },
      { 'http-equiv': 'X-UA-Compatible', content: 'IE=Edge,chrome=1' },
      { name: 'renderer', content: 'webkit' },
      {
        name: 'viewport',
        content:
          'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
      },
      {
        hid: 'description',
        name: 'description',
        content:
          'AIs and categories in the best AI tools directory. AI tools list & GPTs store are updated daily by ChatGPT.',
      },
      {
        hid: 'og:title',
        name: 'og:title',
        content: 'Toolify - Find The Exact AI Tool For Your Needs',
      },
      {
        hid: 'og:description',
        name: 'og:description',
        content:
          'AIs and categories in the best AI tools directory. AI tools list & GPTs store are updated daily by ChatGPT.',
      },
      {
        hid: 'og:type',
        name: 'og:type',
        content: 'website',
      },
      {
        hid: 'og:image',
        name: 'og:image',
        content: 'https://cdn.toolify.ai/default.webp',
      },
      {
        hid: 'og:image:alt',
        name: 'og:image:alt',
        content: 'Toolify - Find The Exact AI Tool For Your Needs',
      },
      {
        hid: 'og:image:width',
        name: 'og:image:width',
        content: '535',
      },
      {
        hid: 'og:image:height',
        name: 'og:image:height',
        content: '332',
      },
      { name: 'format-detection', content: 'telephone=no' },
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      {
        rel: 'alternate',
        hreflang: 'x-default',
        href: 'https://www.toolify.ai/',
      },
      { rel: 'alternate', hreflang: 'de', href: 'https://www.toolify.ai/de/' },
      { rel: 'alternate', hreflang: 'es', href: 'https://www.toolify.ai/es/' },
      { rel: 'alternate', hreflang: 'fr', href: 'https://www.toolify.ai/fr/' },
      { rel: 'alternate', hreflang: 'ja', href: 'https://www.toolify.ai/ja/' },
      { rel: 'alternate', hreflang: 'ko', href: 'https://www.toolify.ai/ko/' },
      { rel: 'alternate', hreflang: 'pt', href: 'https://www.toolify.ai/pt/' },
      {
        rel: 'alternate',
        hreflang: 'zh-TW',
        href: 'https://www.toolify.ai/tw/',
      },
      { rel: 'alternate', hreflang: 'vi', href: 'https://www.toolify.ai/vi/' },
      {
        rel: 'alternate',
        hreflang: 'zh-CN',
        href: 'https://www.toolify.ai/zh/',
      },
    ],
    //TODO 不翻墙会直接500
    script: [
      {
        src: 'https://accounts.google.com/gsi/client',
        async: true,
        body: true,
      },
    ],
  },
  //TODO 预发布端口: 9005 正式环境接口9004
  server: {
    port: 9004,
    host: '0.0.0.0',
  },

  /* watchQuery: true, */

  axios: {
    // 开启代理 (如果需要判断线上线下环境，可以通过 process.env.NODE_ENV !== 'production' 来判断)
    proxy: isDev ? true : false,
    // 跨域请求时是否需要使用凭证
    credentials: true,
  },

  proxy: isDev
    ? {
        '/self-api': {
          // 目标接口域  http://192.168.1.147:8032
          target: 'http://127.0.0.1:8080',
          // 全局配置是否跨域
          changeOrigin: true,
          pathRewrite: {
            // 单个配置是否跨域
            // changeOrigin: true
            // 把 '/api' 替换成 '/'，具体需要替换为 '' 还是 '/' 看自己习惯
            '^/self-api': '/self-api',
          },
        },
        '/common-api': {
          // 目标接口域
          target: 'http://127.0.0.1:8080',
          // 全局配置是否跨域
          changeOrigin: true,
          pathRewrite: {
            // 单个配置是否跨域
            // changeOrigin: true
            // 把 '/api' 替换成 '/'，具体需要替换为 '' 还是 '/' 看自己习惯
            '^/common-api': '/common-api',
          },
        },
        '/gobal': {
          // 目标接口域
          target: 'http://192.168.3.221:8033',
          // 全局配置是否跨域
          changeOrigin: true,
          pathRewrite: {
            // 单个配置是否跨域
            // changeOrigin: true
            // 把 '/api' 替换成 '/'，具体需要替换为 '' 还是 '/' 看自己习惯
            '^/gobal': '/gobal',
          },
        },
      }
    : {},

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
    { src: '@/assets/css/element-variables.scss', lang: 'scss' },
    '@/assets/css/tailwind.css',
    { src: '@/assets/css/style.scss', lang: 'scss' },
    'swiper/dist/css/swiper.css',
  ],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  // 配置文件挂载
  plugins: [
    { src: '@/plugins/axios' },
    '@/plugins/i18n.js',
    '@/plugins/element-ui',
    '@/plugins/svgIcon',
    '@/plugins/echarts',
    '@/plugins/util',
    '@/plugins/util-app',
    '@/plugins/routerReset',
    { src: '@/plugins/swiper', ssr: false },
    { src: '@/plugins/nprogress', ssr: false },
    { src: '@/plugins/directive.js', ssr: false },
    {
      src: '@/plugins/html2canvas.js',
      ssr: false,
    },
    {
      src: '@/plugins/jspdf.js',
      ssr: false,
    },
  ],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: ['@nuxtjs/tailwindcss'],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    '@nuxtjs/axios',
    'cookie-universal-nuxt',
    [
      'nuxt-svg-sprite-loader',
      {
        symbolId: 'icon-[name]',
      },
    ],
    'nuxt-precompress',
    ['@nuxtjs/google-tag-manager', { id: 'GTM-PP3KSMX', pageTracking: true }],
  ],

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    analyze: true,
    publicPath: `/${version}/`,
    transpile: [/^element-ui/],
    // 去掉查看源代码里面的css和window.__NUXT__
    extractCSS: { allChunks: true },

    // 防止重复打包
    vendor: ['axios', 'external library', 'element-ui'],

    //设置Chunks 的最大和最小 size
    optimization: {
      splitChunks: {
        minSize: 10000,
        maxSize: 250000,
      },
    },

    babel: {
      plugins: [
        [
          'component',
          {
            libraryName: 'element-ui',
            styleLibraryName: 'theme-chalk',
          },
        ],
      ],
    },

    plugins: !isDev
      ? [
          new CompressionPlugin({
            test: /\.js$|\.html$|\.css/, // 匹配文件名
            threshold: 10240, // 对超过10kb的数据进行压缩
            deleteOriginalAssets: false, // 是否删除原文件
          }),
        ]
      : [],

    optimization: !isDev
      ? {
          minimize: true,
          splitChunks: {
            chunks: 'all',
            automaticNameDelimiter: '.',
            name: true,
            minSize: 100000,
            maxSize: 1500000,
            cacheGroups: {
              default: false,
              vendor: {
                name: 'node_vendors',
                test: /[\\/]node_modules[\\/]/,
                chunks: 'all',
                minSize: 100000,
                maxSize: 1500000,
              },
              styles: {
                name: 'styles',
                test: /\.(css|vue)$/,
                chunks: 'all',
                enforce: true,
                minSize: 100000,
                maxSize: 1500000,
              },
              commons: {
                test: /node_modules[\\/](vue|vue-loader|vue-router|vuex|vue-meta|core-js|@babel\/runtime|axios|webpack|setimmediate|timers-browserify|process|regenerator-runtime|cookie|js-cookie|is-buffer|dotprop|nuxt\.js)[\\/]/,
                chunks: 'all',
                priority: 10,
                name: true,
              },
            },
          },
        }
      : {},

    SourceMap: isDev ? true : false,
  },

  /* 指定loading页面 */
  loading: '@/components/Loading.vue',

  router: {
    resourceHints: false,
    prefetchLinks: false,
    prefetchPayloads: false,
    middleware: 'i18n',
    scrollBehavior(to, from, savedPosition) {
      if (to.path && from.path && to.path !== from.path) {
        return { x: 0, y: 0 }
      }
    },
    extendRoutes(routes, resolve) {
      routes.push(
        /* {
          path: '/:lang/ai-library',
          component: resolve(__dirname, 'pages/ai-library/index.vue'),
          name: 'lang-ai-library',
        }, */
        /* {
          path: '/:lang/affilate',
          component: resolve(__dirname, 'pages/affilate/index.vue'),
          name: 'lang-affilate',
        }, */
        {
          path: '/:lang/ai-for-capabilities',
          component: resolve(__dirname, 'pages/ai-for-capabilities/index.vue'),
          name: 'lang-ai-for-capabilities',
        },
        {
          path: '/:lang/ai-for-jobs',
          component: resolve(__dirname, 'pages/ai-for-jobs/index.vue'),
          name: 'lang-ai-for-jobs',
        },
        {
          path: '/:lang/alternative/:handle?',
          component: resolve(__dirname, 'pages/alternative/_handle.vue'),
          name: 'lang-alternative-handle',
        },
        {
          path: '/:lang/apps',
          component: resolve(__dirname, 'pages/apps/index.vue'),
          name: 'lang-apps',
        },
        {
          path: '/:lang/Best-AI-Tools-Category/:category?',
          component: resolve(
            __dirname,
            'pages/Best-AI-Tools-Category/_category.vue'
          ),
          name: 'lang-Best-AI-Tools-Category-category',
        },
        {
          path: '/:lang/Best-AI-Tools-region/:region?',
          component: resolve(
            __dirname,
            'pages/Best-AI-Tools-region/_region.vue'
          ),
          name: 'lang-Best-AI-Tools-region-region',
        },
        {
          path: '/:lang/Best-AI-Tools-revenue',
          component: resolve(
            __dirname,
            'pages/Best-AI-Tools-revenue/index.vue'
          ),
          name: 'lang-Best-AI-Tools-revenue',
        },
        {
          path: '/:lang/Best-AI-Tools-Source/:source?',
          component: resolve(
            __dirname,
            'pages/Best-AI-Tools-Source/_source.vue'
          ),
          name: 'lang-Best-AI-Tools-Source-source',
        },
        {
          path: '/:lang/Best-trending-AI-Tools/:month?',
          component: resolve(
            __dirname,
            'pages/Best-trending-AI-Tools/_month.vue'
          ),
          name: 'lang-Best-trending-AI-Tools-month',
        },
        {
          path: '/:lang/browser-extension',
          component: resolve(__dirname, 'pages/browser-extension/index.vue'),
          name: 'lang-browser-extension',
        },
        {
          path: '/:lang/category',
          component: resolve(__dirname, 'pages/category/index.vue'),
          name: 'lang-category',
        },
        {
          path: '/:lang/category/:handle?',
          component: resolve(__dirname, 'pages/category/_handle.vue'),
          name: 'lang-category-handle',
        },
        {
          path: '/:lang/category-attribute/:handle?',
          component: resolve(__dirname, 'pages/category-attribute/_handle.vue'),
          name: 'lang-category-attribute-handle',
        },
        {
          path: '/:lang/compare/:handle?',
          component: resolve(__dirname, 'pages/compare/_handle.vue'),
          name: 'lang-compare-handle',
        },
        {
          path: '/:lang/discord',
          component: resolve(__dirname, 'pages/discord/index.vue'),
          name: 'lang-discord',
        },
        {
          path: '/discord/page/:page?',
          component: resolve(__dirname, 'pages/discord/index.vue'),
          name: 'discord-page-page',
        },
        {
          path: '/:lang/discord/page/:page?',
          component: resolve(__dirname, 'pages/discord/index.vue'),
          name: 'lang-discord-page-page',
        },
        {
          path: '/:lang/discord/:handle?',
          component: resolve(__dirname, 'pages/discord/_handle.vue'),
          name: 'lang-discord-handle',
        },
        {
          path: '/:lang/favorites',
          component: resolve(__dirname, 'pages/favorites/index.vue'),
          name: 'lang-favorites',
        },
        {
          path: '/:lang/forgetPassword',
          component: resolve(__dirname, 'pages/forgetPassword/index.vue'),
          name: 'lang-forgetPassword',
        },
        {
          path: '/:lang/forgetPassword/sendSuccess',
          component: resolve(__dirname, 'pages/forgetPassword/sendSuccess.vue'),
          name: 'lang-forgetPassword-sendSuccess',
        },
        {
          path: '/:lang/free',
          component: resolve(__dirname, 'pages/free/index.vue'),
          name: 'lang-free',
        },
        {
          path: '/:lang/gpts',
          component: resolve(__dirname, 'pages/gpts/index.vue'),
          name: 'lang-gpts',
        },
        {
          path: '/gpts/page/:page?',
          component: resolve(__dirname, 'pages/gpts/index.vue'),
          name: 'gpts-page-page',
        },
        {
          path: '/:lang/gpts/page/:page?',
          component: resolve(__dirname, 'pages/gpts/index.vue'),
          name: 'lang-gpts-page-page',
        },
        {
          path: '/:lang/gpts/:handle?',
          component: resolve(__dirname, 'pages/gpts/_handle.vue'),
          name: 'lang-gpts-handle',
        },
        {
          path: '/:lang/gpts/search/:keyword?',
          component: resolve(__dirname, 'pages/gpts/search/_keyword.vue'),
          name: 'lang-gpts-search-keyword',
        },
        {
          path: '/:lang/gpts-favorites',
          component: resolve(__dirname, 'pages/gpts-favorites/index.vue'),
          name: 'lang-gpts-favorites',
        },
        {
          path: '/:lang/login',
          component: resolve(__dirname, 'pages/login/index.vue'),
          name: 'lang-login',
        },
        {
          path: '/:lang/month/:handle?',
          component: resolve(__dirname, 'pages/month/_handle.vue'),
          name: 'lang-month-handle',
        },
        {
          path: '/:lang/most-saved',
          component: resolve(__dirname, 'pages/most-saved/index.vue'),
          name: 'lang-most-saved',
        },
        {
          path: '/:lang/most-used',
          component: resolve(__dirname, 'pages/most-used/index.vue'),
          name: 'lang-most-used',
        },
        {
          path: '/:lang/new',
          component: resolve(__dirname, 'pages/new/index.vue'),
          name: 'lang-new',
        },
        {
          path: '/:lang/payment',
          component: resolve(__dirname, 'pages/payment/index.vue'),
          name: 'lang-payment',
        },
        {
          path: '/:lang/privacy-policy',
          component: resolve(__dirname, 'pages/privacy-policy/index.vue'),
          name: 'lang-privacy-policy',
        },
        {
          path: '/:lang/register',
          component: resolve(__dirname, 'pages/register/index.vue'),
          name: 'lang-register',
        },
        {
          path: '/:lang/resetPassword',
          component: resolve(__dirname, 'pages/resetPassword/index.vue'),
          name: 'lang-resetPassword',
        },
        {
          path: '/:lang/review/:handle?',
          component: resolve(__dirname, 'pages/review/_handle.vue'),
          name: 'lang-review-handle',
        },
        {
          path: '/:lang/search/:handle?',
          component: resolve(__dirname, 'pages/search/_handle.vue'),
          name: 'lang-search-handle',
        },
        {
          path: '/:lang/submit',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'lang-submit',
        },
        {
          path: '/:lang/submit-success',
          component: resolve(__dirname, 'pages/submit-success/index.vue'),
          name: 'lang-submit-success',
        },
        {
          path: '/:lang/promote',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'lang-promote',
        },
        {
          path: '/promote',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'promote',
        },
        {
          path: '/:lang/advertise',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'lang-advertise',
        },
        {
          path: '/advertise',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'advertise',
        },
        {
          path: '/:lang/submit-gpt',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'lang-submit-gpt',
        },
        {
          path: '/submit-gpt',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'submit-gpt',
        },
        {
          path: '/:lang/update-ai',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'lang-update-ai',
        },
        {
          path: '/update-ai',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'update-ai',
        },
        {
          path: '/:lang/business',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'lang-business',
        },
        {
          path: '/business',
          component: resolve(__dirname, 'pages/submit/index.vue'),
          name: 'business',
        },
        {
          path: '/:lang/success',
          component: resolve(__dirname, 'pages/success/index.vue'),
          name: 'lang-success',
        },

        //标签详情页
        {
          path: '/:lang/tag/:handle?',
          component: resolve(__dirname, 'pages/tag/_handle.vue'),
          name: 'lang-tag-handle',
        },
        {
          path: '/:lang/tool/:handle?',
          component: resolve(__dirname, 'pages/tool/_handle.vue'),
          name: 'lang-tool-handle',
        },
        {
          path: '/:lang/top-ai-tools',
          component: resolve(__dirname, 'pages/top-ai-tools/index.vue'),
          name: 'lang-top-ai-tools',
        },
        {
          path: '/top-ai-tools/page/:page?',
          component: resolve(__dirname, 'pages/top-ai-tools/index.vue'),
          name: 'top-ai-tools-page-page',
        },
        {
          path: '/:lang/top-ai-tools/page/:page?',
          component: resolve(__dirname, 'pages/top-ai-tools/index.vue'),
          name: 'lang-top-ai-tools-page-page',
        },
        {
          path: '/:lang/top-ai-tools/:handle?',
          component: resolve(__dirname, 'pages/top-ai-tools/_handle.vue'),
          name: 'lang-top-ai-tools-handle',
        },
        {
          path: '/:lang/tool-update/:handle?',
          component: resolve(__dirname, 'pages/tool-update/_handle.vue'),
          name: 'lang-tool-update-handle',
        },
        {
          path: '/:lang/user',
          component: resolve(__dirname, 'pages/user/index.vue'),
          name: 'lang-user',
        },
        {
          path: '/:lang',
          component: resolve(__dirname, 'pages/index.vue'),
          name: 'lang-index',
        }
      )

      /* if (process.browser) {
        this.afterEach(() => {
          this.$nextTick(() => {
            window.scrollTo(0, 0)
          })
        })
      } */
    },
  },

  purgeCSS: !isDev
    ? {
        enabled: false,
      }
    : {},

  //nuxt项目也开启gzip、br
  nuxtPrecompress: !isDev
    ? {
        gzip: {
          enabled: true,
          filename: '[path].gz[query]',
          threshold: 5120,
          minRatio: 0.8,
          compressionOptions: { level: 9 },
        },
        brotli: {
          enabled: true,
          filename: '[path].br[query]',
          compressionOptions: { level: 11 },
          threshold: 5120,
          minRatio: 0.8,
        },
        enabled: true,
        report: false,
        test: /\.(js|css|html|txt|xml|svg)$/,
        // Serving options
        middleware: {
          enabled: true,
          enabledStatic: true,
          encodingsPriority: ['br', 'gzip'],
        },
      }
    : {},
}
